<?php


namespace App\Web\Controller;

use App\Web\Facades\UserAuth;
use App\Web\Model\Project;
use App\Web\Model\Login as LoginModel;
use App\Web\Model\RabbitMQ\NoticeProducer;
use App\Web\Model\User as UserModel;
use App\Web\Service\RightCheck;
use EchoPHP\Http\Request;
use App\Web\Model\Customer as CustomerModel;
use App\Service\Crmapi as crm;
use App\Web\Model\CaseFlow;
use EchoPHP\Validator\Validator;

class Customer extends Controller {

    public $rightCheck = [
        'add' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'crmSync' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'addOperator' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'transferCharger' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'delOperator' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'editFlow' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'show' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'GetprojectList' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
//        'projToCustomer' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
//        'caseToCustomer' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
//        'caseToProj' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'detail' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'crmInfo' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'showOperator' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
//        'getSubFlow' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'getChoseSubFlow' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'getDefaultList' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'getAllCustomer' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
        'edit' => RightCheck::RIGHT_CUSTOMERCOMPANY_ALL,
    ];

    /**添加客户
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function add(Request $request) {
        $params = [
            'creator' => $this->getLoginId(),
            'crmsubid' => $request->getPost('crmsubid'),
            'charger' => $request->getPost('charger/d'),
            'oprId' => $request->getPost('oprid'),
            'tagCode' => $request->getPost('tagcode'),
            'subshowname' => $request->getPost('subshowname'),
            'introduce' => $request->getPost('introduce'),
            'account' => $request->getPost('account'),
        ];
        $customerModel = new CustomerModel();
        $result = $customerModel->Add($params);

        if ($result['status']) {
            //新增客户，异步发送通知
            $noticeProducer = new NoticeProducer();
            $noticeProducer->add(NoticeProducer::MODULE_CUSTOMER_ADD, [
                'subid' => $result['subid'],
                'handlerid' => UserAuth::getLoginId(),
                'handlername' => UserAuth::getLoginCname(),
            ]);
        }

        return $this->json($result);
    }


    /**同步客户信息
     * @param Request $request
     * @return mixed
     */
    public function crmSync(Request $request) {
        $subId = $request->getPost('subid');
        $crmSubId = $request->getPost('crmsubid');
        $updator = $this->getLoginId();
        $customerModel = new CustomerModel();
        $result = $customerModel->customerSync($updator, $subId, $crmSubId);
        if ($result['status']) {
            $noticeProducer = new NoticeProducer();
            $noticeProducer->add(NoticeProducer::MODULE_CUSTOMER_EDIT, [
                'subid' => $subId,
                'handlerid' => UserAuth::getLoginId(),
                'handlername' => UserAuth::getLoginCname(),
                'description' => '同步获取CRM客户信息',
            ]);
        }
        return $this->json($result);
    }

    /**
     * Notes:客户执行人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     */
    public function showOperator(Request $request) {
        $subId = $request->getParam('subid');
        $customerModel = new CustomerModel();
        $oprList = $customerModel->GetSubOpr($subId);
        return $this->json([
            'status' => true,
            'message' => '查询成功',
            'oprlist' => $oprList
        ]);
    }

    /**
     * Notes:添加客户执行人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     */
    public function addOperator(Request $request) {
        $oprIds = $request->getParam('oprid', []);
        $subId = $request->getParam('subid');
        $customerModel = new CustomerModel();
        if (!$customerModel->chkEditSubRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        $result = $customerModel->addSubOpr($oprIds, $subId);

        if ($result) {
            $noticeProducer = new NoticeProducer();
            $noticeProducer->add(NoticeProducer::MODULE_CUSTOMER_EDIT, [
                'subid' => $subId,
                'handlerid' => UserAuth::getLoginId(),
                'handlername' => UserAuth::getLoginCname(),
                'description' => '新增客户执行人(userid: ' . implode(',', $oprIds) . ')',
            ]);
        }

        return $this->json([
            'status' => $result,
            'message' => $result ? '操作成功' : '操作失败'
        ]);
    }

    /**
     * Notes:转让客户负责人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     */
    public function transferCharger(Request $request) {
        $oprId = $request->getParam('oprid');
        $subId = $request->getParam('subid');
        $customerModel = new CustomerModel();
        if (!$customerModel->chkEditSubRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        $result = $customerModel->transferSubCharger($oprId, $subId);

        if ($result) {
            $noticeProducer = new NoticeProducer();
            $noticeProducer->add(NoticeProducer::MODULE_CUSTOMER_EDIT, [
                'subid' => $subId,
                'handlerid' => UserAuth::getLoginId(),
                'handlername' => UserAuth::getLoginCname(),
                'description' => '修改负责人(userid:' . $oprId . ')',
            ]);
        }

        return $this->json([
            'status' => $result,
            'message' => $result ? '操作成功' : '操作失败'
        ]);
    }

    /**
     * Notes:单条删除客户执行人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     */
    public function delOperator(Request $request) {
        $oprId = $request->getParam('oprid');
        $subId = $request->getParam('subid');
        $customerModel = new CustomerModel();
        if (!$customerModel->chkEditSubRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        $result = $customerModel->delSubOpr($oprId, $subId);

        if ($result) {
            $noticeProducer = new NoticeProducer();
            $noticeProducer->add(NoticeProducer::MODULE_CUSTOMER_EDIT, [
                'subid' => $subId,
                'handlerid' => UserAuth::getLoginId(),
                'handlername' => UserAuth::getLoginCname(),
                'description' => '删除客户执行人(userid:' . $oprId . ')',
            ]);
        }

        return $this->json([
            'status' => $result,
            'message' => $result ? '操作成功' : '操作失败'
        ]);
    }

    /**更新交易公司流程
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function editFlow(Request $request) {
        $updator = $this->getLoginId();
        $subId = $request->getPost('subid');
        $tagCode = $request->getPost('tagcode');    //逗号分隔的字符串

        $customerModel = new CustomerModel();
        $result = $customerModel->updateSubFlow($updator, $subId, $tagCode);

        if ($result['status']) {
            $noticeProducer = new NoticeProducer();
            $noticeProducer->add(NoticeProducer::MODULE_CUSTOMER_EDIT, [
                'subid' => $subId,
                'handlerid' => UserAuth::getLoginId(),
                'handlername' => UserAuth::getLoginCname(),
                'description' => '编辑客户所属操作标签流程',
            ]);
        }

        return $this->json($result);
    }

    /**获取客户列表
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function show(Request $request) {
        $pageNum = $request->getPost('pagenum/d', 1);
        $pageLimit = $request->getPost('pagelimit/d', 20);
        $params = [
            'subid' => $request->getPost('subid'),
            'subname' => $request->getPost('subname'),
            'crmsubid' => $request->getPost('crmsubid'),
            'subarea' => $request->getPost('subarea'),
        ];
        $customerModel = new CustomerModel();
        list($pageNum, $rowFrom, $rowTo) = $customerModel->paginationParameters($pageNum, $pageLimit);
        $count = $customerModel->myCostumer($params, 'count')['count'];
        $customerList = [];
        if ($count) {
            $customerList = $customerModel->myCostumer($params, '', $rowFrom, $rowTo);
        }
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'totalcount' => intval($count),
                'pagenum' => $pageNum,
                'customerlist' => $customerList,
            ]
        );
    }

    /**编辑客户显示名称和介绍
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function edit(Request $request) {
        $subId = $request->getPost('subid');
        $subShowName = $request->getPost('subshowname');
        $introduce = $request->getPost('introduce');
        $updator = $this->getLoginId();
        $customerModel = new CustomerModel();
        $result = $customerModel->editShowInfo($subId, $subShowName, $introduce, $updator);

        if ($result['status']) {
            $noticeProducer = new NoticeProducer();
            $noticeProducer->add(NoticeProducer::MODULE_CUSTOMER_EDIT, [
                'subid' => $subId,
                'handlerid' => UserAuth::getLoginId(),
                'handlername' => UserAuth::getLoginCname(),
                'description' => '编辑客户基本信息',
            ]);
        }

        return $this->json($result);
    }

    /**查询交易公司所对应的信息
     * @param Request $request
     */
    public function detail(Request $request) {
        $subId = $request->getParam('subid/d');
        $customerModel = new CustomerModel();
        $subInfo = $customerModel->detail($subId);
        return $this->json($subInfo);
    }


    //创建项目时所专用客户列表
    public function projToCustomer() {
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'sublist' => $this->getCustomer('project')
            ]
        );
    }

    private function getCustomer($field = '') {
        $customerModel = new CustomerModel();
        $userid = UserAuth::getLoginId();
        $customerList = $oprSubList = [];
        if (UserAuth::getLoginInfo('issuper', '') == 1) {
            $customerModel = new CustomerModel();
            $customerList = $customerModel->search('', '', 0, 0, 'subid,subname,crmsubid');
            return $customerList;
        }

        //作为客户对接人
        $oprSubList = $customerModel->oprSubList($userid);
        //作为项目对接人
        if ($field != 'project') {
            $customerList = $customerModel->oprProjList($userid);
        }
        //去重
        foreach ($oprSubList as $key => $sub) {
            if (in_array($sub['subid'], array_column($customerList, 'subid'))) {
                unset($oprSubList[$key]);
            }
        }
        return array_merge($oprSubList, $customerList);
    }

    //创建职位时所专用客户列表
    public function caseToCustomer() {
        $mySubList = (new Project())->myProject([], 'distinct cs.subid,cs.crmsubid,cs.subname');
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'subList' => $mySubList,
            ]
        );
    }

    //创建职位专用客户列表查询其下项目
    public function caseToProj(Request $request) {
        $subid = $request->getParam('subid');
        $projectList = (new Project())->myProject(['subid' => $subid], 'p.projectid,p.crmprojectnum,p.projectname');
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'projectList' => $projectList,
            ]
        );

    }

    /**查询CRM公司信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function crmInfo(Request $request) {
        $crmSubId = $request->getParam('crmsubid/d');

        $customerModel = new CustomerModel();
        $result = $customerModel->chkcrmsubid($crmSubId);
        if (!$result['status']) {
            return $this->json($result);
        }
        $crmService = new crm();
        $crmCustomerInfo = $crmService->getCrmCustomerInfo($crmSubId);
        if (empty($crmCustomerInfo)) {
            return $this->json(['status' => false, 'message' => '未查到记录', 'crmcustomerInfo' => []]);
        } else {
            $result = [
                'crmsubid' => $crmSubId,
                'subname' => $crmCustomerInfo['subname'],
                'subarea' => $crmCustomerInfo['branch'],
                'selleremail' => $crmCustomerInfo['email'],
                'sellerid' => $crmCustomerInfo['oprid'],
                'sellername' => $crmCustomerInfo['oprname'],
                'sellerphone' => $crmCustomerInfo['phone'],
                'industry' => $crmCustomerInfo['industry'] ?? '',
                'leadername' => $crmCustomerInfo['reporttoname'] ?? '',
                'leaderid' => $crmCustomerInfo['reportto'],
                'leaderphone' => $crmCustomerInfo['reporttophone'],
                'leaderemail' => $crmCustomerInfo['reporttoemail'],
            ];
            return $this->json(['status' => true, 'message' => '查找成功', 'crmcustomerInfo' => $result]);
        }
    }

    /**获取交易公司的流程
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getSubFlow(Request $request) {
        $subId = $request->getParam('subId');
        $customerModel = new CustomerModel();
        $hasRight = $customerModel->hasSubIdRight($subId);
        if (!$hasRight) {
            return $this->json([
                'status' => '',
                'message' => '无权限',
                'flowlist' => []
            ]);
        }
        $caseFlowModel = new CaseFlow();
        $subFlowList = $caseFlowModel->getSubFlowFull($subId, true);
        return $this->json([
            'status' => empty($subFlowList) ? false : true,
            'message' => empty($subFlowList) ? '该客户尚未定义流程标签' : '获取成功',
            'flowlist' => $caseFlowModel->transFlowToNotAssoc($subFlowList)
        ]);
    }

    /**获取交易公司的流程
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getChoseSubFlow(Request $request) {
        $subId = $request->getParam('subid');
        $caseFlowModel = new CaseFlow();
        $flowList = $caseFlowModel->getSubFlow($subId);

        return $this->json([
            'status' => empty($flowList) ? false : true,
            'message' => empty($flowList) ? '该客户尚未定义流程标签' : '获取成功',
            'flowlist' => $caseFlowModel->transFlowToNotAssoc($flowList)
        ]);
    }


    /**获取完整的客户流程表
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getDefaultList() {
        $caseFlowModel = new CaseFlow();
        $flowList = $caseFlowModel->getDefaultFlow(true);
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'flowlist' => $caseFlowModel->transFlowToNotAssoc($flowList)
        ]);
    }

    /**获取客户列表,用于选择客户
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getAllCustomer(Request $request) {
        $customerModel = new CustomerModel();
        $customerList = $customerModel->search('', '', 0, 0, 'subid,subname,updatedate');
        $customerList = multiSort($customerList, ['updatedate' => SORT_ASC]);
        if (empty($customerList)) {
            return $this->json(['status' => true, 'message' => '获取失败', 'customerlist' => []]);
        } else {
            return $this->json(['status' => true, 'message' => '获取成功', 'customerlist' => $customerList]);
        }
    }


    /**获取交易公司下的面试官信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getSubInterviewer(Request $request) {
        $subId = $request->getParam('subid');
        $customerModel = new CustomerModel();

        if (!$customerModel->chkEditSubInterviewerRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权获取该客户的面试官']);
        }

        $result = $customerModel->showSubInterviewer($subId);

        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'list' => $result
        ]);
    }

    /**新增交易公司下的面试官信息（被新增客户联系人取代）
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function addSubInterviewer(Request $request) {
        $params = [
            'subid' => $request->getParam('subid'),
            'cname' => $request->getParam('cname'),
            'mobilephone' => $request->getParam('mobilephone'),
            'email' => $request->getParam('email'),
            'department' => $request->getParam('department'),
            'memo' => $request->getParam('memo'),
        ];

        $rule = [
            'subid|交易公司id' => [
                'required', 'number'
            ],
            'cname|面试官姓名' => [
                'required', 'minLength' => 1, 'maxLength' => 20
            ],
            'mobilephone|面试官手机' => [
                'required', 'minLength' => 7, 'maxLength' => 19
            ],
            'email|面试官邮箱' => [
                'email', 'maxLength' => 50
            ],
            'department|部门' => [
                'maxLength' => 50
            ],
            'memo|备注' => [
                'maxLength' => 200
            ],
        ];
        $validate = new Validator($rule);
        if (!$validate->validate($params)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ]);
        }

        if ((preg_match('/(^(((\+)?\d{1,4}-)\d{5,15}$)|(^1\d{10}$))/', $params['mobilephone']) == 0) && (preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?(\(0\d{2,3}\)|0\d{2,3})?(\(0\d{2,3}\)|0\d{2,3})?[1-9]\d{6,7}(\-\d{1,5})?$/', $params['mobilephone']) == 0)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '手机/座机格式不正确']
            ]);
        }

        $params['mobilephone'] = ltrim($params['mobilephone'], '+');
        $phoneArr = explode("-", $params['mobilephone']);
        if (count($phoneArr) == 2) {
            if ($phoneArr[0] == 86) {
                $params['mobilephone'] = $phoneArr[1];
            } else {
                // $params['mobilephone'] = ltrim($params['mobilephone'], 0);
            }
        }

        $userId = UserAuth::getLoginId();
        $subId = $params['subid'];

        $customerModel = new CustomerModel();

        if (!$customerModel->chkEditSubInterviewerRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权添加该客户的面试官']);
        }

        $result = $customerModel->addSubInterviewer($userId, $subId, $params);
        return $this->json($result);
    }

    /**编辑交易公司下的面试官信息（已被编辑客户联系人代替）
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function editSubInterviewer(Request $request) {
        $params = [
            'subid' => $request->getParam('subid'),
            'accountid' => $request->getParam('accountid'),
            'cname' => $request->getParam('cname'),
            'mobilephone' => $request->getParam('mobilephone'),
            'email' => $request->getParam('email'),
            'department' => $request->getParam('department'),
            'memo' => $request->getParam('memo'),
        ];

        $rule = [
            'subid|交易公司id' => [
                'required', 'number'
            ],
            'accountid|面试官id' => [
                'required', 'number'
            ],
            'cname|面试官姓名' => [
                'required', 'minLength' => 1, 'maxLength' => 20
            ],
            'mobilephone|面试官手机' => [
                'required', 'minLength' => 7, 'maxLength' => 19
            ],
            'email|面试官邮箱' => [
                'email', 'maxLength' => 50
            ],
            'department|部门' => [
                'maxLength' => 50
            ],
            'memo|备注' => [
                'maxLength' => 200
            ],
        ];
        $validate = new Validator($rule);
        if (!$validate->validate($params)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ]);
        }
        if ((preg_match('/(^(((\+)?\d{1,4}-)\d{5,15}$)|(^1\d{10}$))/', $params['mobilephone']) == 0) && (preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?(\(0\d{2,3}\)|0\d{2,3})?(\(0\d{2,3}\)|0\d{2,3})?[1-9]\d{6,7}(\-\d{1,5})?$/', $params['mobilephone']) == 0)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '手机/座机格式不正确']
            ]);
        }

        $params['mobilephone'] = ltrim($params['mobilephone'], '+');
        $phoneArr = explode("-", $params['mobilephone']);
        if (count($phoneArr) == 2) {
            if ($phoneArr[0] == 86) {
                $params['mobilephone'] = $phoneArr[1];
            } else {
                // $params['mobilephone'] = ltrim($params['mobilephone'], 0);
            }
        }

        $userId = UserAuth::getLoginId();
        $subId = $params['subid'];
        $accountId = $params['accountid'];
        $customerModel = new CustomerModel();

        if (!$customerModel->chkEditSubInterviewerRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户的面试官']);
        }

        $result = $customerModel->editSubInterviewer($userId, $subId, $accountId, $params);
        return $this->json($result);
    }

    /**删除交易公司下的面试官信息（已被删除客户联系人代替）
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function delSubInterviewer(Request $request) {
        $params = [
            'subid' => $request->getParam('subid'),
            'accountid' => $request->getParam('accountid'),
        ];

        $rule = [
            'subid|交易公司id' => [
                'required', 'number'
            ],
            'accountid|面试官id' => [
                'required', 'number'
            ]
        ];

        $validate = new Validator($rule);
        if (!$validate->validate($params)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ]);
        }

        $userId = UserAuth::getLoginId();
        $subId = $params['subid'];
        $accountId = $params['accountid'];
        $customerModel = new CustomerModel();

        if (!$customerModel->chkEditSubInterviewerRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权删除该客户的面试官']);
        }

        $result = $customerModel->delSubInterviewer($userId, $subId, $accountId);
        return $this->json($result);
    }

    /**
     * Notes:客户下的项目
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function ProjectList(Request $request) {
        $subId = $request->getParam('subid');
        $customerModel = new CustomerModel();
        if (!$customerModel->chkEditSubInterviewerRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权获取该客户项目列表']);
        }
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'projectlist' => $customerModel->projectList($subId)
        ]);
    }
}